package com.cskt.petproject178.config;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * 订单延时处理配置类
 *
 * @author 27013
 **/

@Configuration
public class OrderDelayQueueConfig {
    // 准备正常订单相关的队列以及交换机
    public static  final  String ORDER_EXCHANGE_NAME="order_exchange";
    public static final  String ORDER_QUEUE_NAME="order_queue";
    //死信队列以及交换机
    public static  final  String ORDER_DELAY_EXCHANGE_NAME="order_delay_exchange";
    public static final  String ORDER_DELAY_QUEUE_NAME="order_delay_queue";

    //正常订单/死信队列与交换机路由key
    public  static  final String ORDER_ROUTING_KEY="order_routing_key";
    public  static  final String ORDER_DELAY_ROUTING_KEY="order_delay_routing_key";

    /**
     *  准备正常订单队列交换机
     * @return
     */
    @Bean
    public Exchange orderExchange(){
      return   ExchangeBuilder.directExchange(ORDER_EXCHANGE_NAME).build();
    }

    @Bean
    public Queue orderQueue(){
        Map<String,Object> arguments=new HashMap<>();
        //死信队列交换机，当正常队列中的消息超时后，则会通过交换机转入死信队列
        arguments.put("x-dead-letter-exchange",ORDER_DELAY_EXCHANGE_NAME);
        //死信队列的路由key，用于绑定
        arguments.put("x-dead-letter-routing-key",ORDER_DELAY_ROUTING_KEY);
        return QueueBuilder.durable(ORDER_QUEUE_NAME)
                //自定义参数，主要用于绑定过期时间
        .withArguments(arguments).build();
    }

    /**
     * 将正常的队列与正常的交换机绑定到一起
     * @return
     */
    @Bean
    public Binding orderBinding(){
        return BindingBuilder
                //指定正常订单队列
                .bind(orderQueue())
                //指定正常订单交换机
                .to(orderExchange())
                //通过路由key进行绑定
                .with(ORDER_ROUTING_KEY).noargs();
    }


    /**
     *  死信队列交换机
     * @return
     */
    @Bean
    public Exchange orderDelayExchange(){
        return ExchangeBuilder.directExchange(ORDER_DELAY_EXCHANGE_NAME).build();
    }

    /**
     * 死信队列
     * @return
     */
    @Bean
    public Queue orderDelayQueue(){
        return QueueBuilder.durable(ORDER_DELAY_QUEUE_NAME).build();
    }

    /**
     * 将死信队列与死信交换机绑定到一起
     * @return
     */
    @Bean
    public Binding orderDelayBinding(){
        return BindingBuilder.bind(orderDelayQueue()).to(orderDelayExchange()).with(ORDER_DELAY_ROUTING_KEY).noargs();
    }
}
